package com.zhz.service.role;

import java.util.List;

import com.zhz.dao.role.RoleMapper;
import com.zhz.dao.user.UserMapper;
import com.zhz.entity.Role;
import com.zhz.service.role.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Transactional
@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Role> findRolesByName(String roleName) {
        try {
            return roleMapper.getRoleListByRoleName(roleName);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
    }

    @Override
    public boolean addNewRole(Role role) {
        boolean result = false;
        try {
            if (roleMapper.add(role) == 1)
                result = true;
            // int i = 1 / 0;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public boolean modifyRole(Role role) {
        boolean result = false;
        try {
            if (roleMapper.modify(role) == 1)
                result = true;
            // int i = 1 / 0;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

    @Override
    public boolean deleteRole(Integer roleId) {
        boolean result = false;
        try {
            if (roleMapper.getUserCountByRoleId(roleId) > 0)
                userMapper.deleteUserByRoleId(roleId);
            if (roleMapper.deleteRoleById(roleId) == 1)
                result = true;
            // int i = 1 / 0;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw e;
        }
        return result;
    }

}
